package com.runme.chatrobot;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.runme.chatrobot.commons.Constants;
import com.runme.chatrobot.models.ChatMsg;
import com.runme.chatrobot.utils.HttpUtil;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    private ListView listView;
    private Button sendButton;
    private EditText editText;
    private List<ChatMsg> msgs=new ArrayList<>(16);
    private  ArrayAdapter<ChatMsg> adapter;
    private Handler httpHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
           String result= (String) msg.obj;
            ChatMsg from=new ChatMsg(result.substring(0,result.lastIndexOf('}')+1), ChatMsg.Type.FROM);
            msgs.add(from);
            adapter.notifyDataSetChanged();
            listView.setSelection(msgs.size());
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView= (ListView) findViewById(R.id.chat_msg);
        editText= (EditText) findViewById(R.id.input_msg);
        sendButton= (Button) findViewById(R.id.send_button);

        InitData();

        adapter =new ArrayAdapter<ChatMsg>(MainActivity.this,R.layout.listview_item_chat_content,msgs){
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ChatMsg msg=msgs.get(position );
                View  view;
                ViewHolder viewHolder;
                if (convertView==null){
                    view= LayoutInflater.from(getContext()).inflate(R.layout.listview_item_chat_content,null);
                    viewHolder=new ViewHolder();
                    viewHolder.from_layout= (LinearLayout) view.findViewById(R.id.from_layout);
                    viewHolder.to_layout= (LinearLayout) view.findViewById(R.id.to_layout);
                    viewHolder.from_text= (TextView) view.findViewById(R.id.from_text);
                    viewHolder.to_text= (TextView) view.findViewById(R.id.to_text);
                    viewHolder.msg_date=(TextView) view.findViewById(R.id.msg_date);
                    view.setTag(viewHolder);
                }else {
                    view= convertView;
                    viewHolder= (ViewHolder) view.getTag();
                }
                viewHolder.msg_date.setText(msg.getDate());
                if (msg.getType()== ChatMsg.Type.FROM){
                    viewHolder.from_layout.setVisibility(View.VISIBLE);
                    viewHolder.to_layout.setVisibility(View.GONE);
                    String content=msg.getContent();
                    try {
                        JSONObject from= JSON.parseObject(content);
                        String response=from.getString("text");
                        viewHolder.from_text.setText(response);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        viewHolder.from_text.setText("服务器异常！");
                    }
                }else if (msg.getType()== ChatMsg.Type.TO){
                    viewHolder.from_layout.setVisibility(View.GONE);
                    viewHolder.to_layout.setVisibility(View.VISIBLE);
                    String content=msg.getContent();
                   viewHolder.to_text.setText(content);
                }
                return  view;
            }
            class ViewHolder {
                LinearLayout from_layout;
                LinearLayout to_layout;
                TextView from_text;
                TextView to_text;
                TextView msg_date;
            }
        };

        listView.setAdapter(adapter);

        //add listener 添加事件监听器
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Editable msg=editText.getText();
                if (msg==null){
                    Toast.makeText(MainActivity.this,"请输入发送内容",Toast.LENGTH_LONG).show();
                }
                else{
                    ChatMsg data=new ChatMsg(msg.toString(), ChatMsg.Type.TO);
                    msgs.add(data);
                    editText.setText("");
                    adapter.notifyDataSetChanged();
                   String param="";
                    try {
                        param =  URLEncoder.encode(msg.toString(), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    final String  url=Constants.robotURL+param;

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d("DEBUG", url);
                           String result= HttpUtil.doGet(url);

                            Log.d("DEBUG", result);
                            Message msg=Message.obtain();
                            msg.obj=result;
                            httpHandler.sendMessage(msg);
                        }
                    }).start();




                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void InitData() {
        ChatMsg welcome=new ChatMsg("{\"text\":\"很高兴见到你，屌丝同学！\"}", ChatMsg.Type.FROM);
        msgs.add(welcome);
    }

}
